package com.haoniu.common.utils.sms;

import com.alibaba.fastjson.JSON;
import com.haoniu.common.config.Global;
import com.haoniu.common.utils.YamlUtil;
import com.haoniu.common.utils.sms.chuanglan.ChuangLanSmsUtil;
import com.haoniu.common.utils.sms.chuanglan.request.SmsSendRequest;
import com.haoniu.common.utils.sms.chuanglan.response.SmsSendResponse;

import java.text.MessageFormat;

/**
 * 描述:
 *
 * @author fei
 * @create 2019-03-19 10:54
 */
public class ChuangLanSms {

    /**
     * 创蓝253 API账号 - 示例 N1234567
     */
    private static String API_ACCOUNT ;

    /**
     * 创蓝253 密码
     */
    private static String API_SECRET ;

    private static String MSG_MODEL ;

    private static String ENV = "dev";

    static {
        ENV = Global.getConfig("spring.profiles.active");
        API_ACCOUNT = YamlUtil.getProperty("application-" + ENV + ".yml","sms.chuangLan.apiAccount");
        API_SECRET = YamlUtil.getProperty("application-" + ENV + ".yml","sms.chuangLan.apiSecret");
        MSG_MODEL = YamlUtil.getProperty("application-" + ENV + ".yml","sms.chuangLan.msgModel");
    }

    /**
     * 创蓝253 请求账户地址
     */
    private static String API_REQUEST_URL= "http://smssh1.253.com/msg/send/json";

    public static void main(String[] args) {
        send("18715083549","987971");
    }

    /**
     * 发送普通短信验证码
     */
    public static boolean send(String phoneNum, String code) {
        try {
            String msgContent = MessageFormat.format(MSG_MODEL, code);
            SmsSendRequest smsSingleRequest = new SmsSendRequest(API_ACCOUNT, API_SECRET, msgContent, phoneNum,"true");
            String requestJson = JSON.toJSONString(smsSingleRequest);
            System.out.println("创蓝253短信原始请求报文: " + requestJson);
            String response = ChuangLanSmsUtil.sendSmsByPost(API_REQUEST_URL, requestJson);
            System.out.println("创蓝253短信响应报文 :" + response);
            SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);
            if("0".equals(smsSingleResponse.getCode())){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}
